package com.tqfframe.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;


/**
 * @Author: 唐祺峰
 * @Service 在调用服务之前执行，我最先进行过滤，可以在里面定义token认证等。
 * @Date: 2022/2/8 0008 16:12
 * @Version 1.0
 */
public class PreFilter extends ZuulFilter {

    Logger logger = LoggerFactory.getLogger(PreFilter.class);

    @Override
    public String filterType() {
//        return FilterConstants.ERROR_TYPE;
        return "pre";
    }

    @Override
    public int filterOrder() {
        //优先级，数字越大，优先级越低
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        logger.info("我最先执行");
        //是否执行该过滤器，true代表需要过滤
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        logger.info("send {} request to {}", request.getMethod(), request.getRequestURL().toString());
        //获取传来的参数accessToken
        Object accessToken = request.getParameter("accessToken");

//        if(accessToken == null) {
        if(false) {
            logger.warn("access token is empty");
            //过滤该请求，不往下级服务去转发请求，到此结束
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            ctx.setResponseBody("{\"result\":\"accessToken为空!\"}");
            ctx.getResponse().setContentType("text/html;charset=UTF-8");
            return null;
        }
        //如果有token，则进行路由转发
        logger.info("access token ok");
        //这里return的值没有意义，zuul框架没有使用该返回值
        return null;
    }

}